package com.qdxwx.web.controller.auth;


import com.qdxwx.captcha.Constants;
import com.qdxwx.common.cache.CacheUtils;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKRequest;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.common.wechat.WxLogin;
import com.qdxwx.data.service.user.UserLoginService;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.models.user.User;
import com.qdxwx.models.user.UserToken;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.util.Map;

/**
 * 个人中心  Controller
 * @author developer
 */
@Controller
@RequestMapping("/auth")
public class LoginController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private WebsiteProfileService websiteProfileService;

    @RequestMapping(value = {"/default.html", "/login.html"}, method = RequestMethod.GET)
    public String showLogin(HttpServletRequest request,
                            Map<String, Object> model) {

        String comeUrl = TKRequest.getComeUrl(request);

        if (LoginUser.getUserId(request) > 0) {
            return "redirect:" + comeUrl;
        }

        if (WxLogin.isWxBrowser(request)) {
            //微信内置浏览器
            return "redirect:/auth/wechat/login?come_url=" + comeUrl;
        }

        if (comeUrl.charAt(0) == '/') {
            comeUrl = "https://" + request.getServerName() + comeUrl;
        }

        String state = TKString.createUUID();
        HttpSession session = request.getSession();
        session.setAttribute(WeChatLoginController.SESSION_STATE_NAME, state);
        session.setAttribute(WeChatLoginController.SESSION_COMEURL_NAME, TKConvert.toURLEncode(comeUrl));
        Map<String, Object> wxConfig = websiteProfileService.getMap("wxLogin");

        String base_url = "https://" + request.getServerName() + "/auth/wechat";
        model.put("comeUrl", comeUrl);
        model.put("appId", wxConfig.get("appId"));
        model.put("redirectUri", TKConvert.toURLEncode(base_url + "/return"));
        model.put("state", state);
        if (TKRequest.isMobileBrowse(request)) {
            return getViewPath("auth/login-mobile");
        } else {
            return getViewPath("auth/login");
        }
    }

    /**
     * 执行登录
     */
    @RequestMapping("/login.json")
    @ResponseBody
    public AjaxResult userLogin(HttpServletRequest request, HttpServletResponse response) {
        int loginType = TKConvert.toInteger(request.getParameter("type"));
        User user;
        if (loginType == 2) {
            String mobile = request.getParameter("mobile");
            String mobileCode = request.getParameter("mobileCode");
            if (TKString.isEmpty(mobileCode)) {
                return AjaxResult.error("请输入手机登录码");
            }
            //验证账号为手机格式登陆时返回下面提示
            if (!TKString.isMobile(mobile)) {
                return AjaxResult.error("请输入正确的手机号码");
            }
            try {
                CacheUtils.checkMobileCode(mobile, mobileCode);
            } catch (Exception ex) {
                return AjaxResult.error(ex.getMessage());
            }
            user = userService.getByMobile(mobile);
            if (user == null) {
                return AjaxResult.error("账号不存在！");
            }
        } else {
            String account = request.getParameter("account");
            String password = request.getParameter("password");
            String ranCode = request.getParameter("ranCode");
            if (TKString.isEmpty(account)) {
                return AjaxResult.error("请输入手机号/账户/邮箱");
            }
            if (TKString.isEmpty(password)) {
                return AjaxResult.error("请输入登录密码");
            }
            if (TKString.isEmpty(ranCode)) {
                return AjaxResult.error("请输入验证码");
            }
            String sessionCode = (String) request.getSession().getAttribute(Constants.CAPTCHA_SESSION_KEY);
            if (TKString.isEmpty(sessionCode) || !sessionCode.equals(ranCode)) {
                return AjaxResult.error("验证码验证失败");
            }
            user = userService.getByLoginName(account);
            if (user == null) {
                return AjaxResult.error("账号不存在或密码错误");
            }
            if (!user.getPassword().equals(TKConvert.toMD5(password))) {
                return AjaxResult.error("账号不存在或密码错误");
            }
        }

        if (user.getIsAvailable() == 2) {
            return AjaxResult.error("帐号已被禁用");
        }

        UserToken token = userService.doLogin(request, user);
        LoginUser.setUser(request, user);
        LoginUser.setCookie(response, token);

        return AjaxResult.success(user);
    }

    @RequestMapping(value = "/privacy.html", method = RequestMethod.GET)
    public String privacy(HttpServletRequest request,
                          Map<String, Object> model) {
        return getViewPath("auth/privacy");
    }

    @RequestMapping(value = "/clause.html", method = RequestMethod.GET)
    public String clause(HttpServletRequest request,
                         Map<String, Object> model) {
        return getViewPath("auth/clause");
    }
}